package com.example.se.controller;


import com.example.se.common.BaseResponse;
import com.example.se.common.ErrorCode;
import com.example.se.common.utils.ResultUtils;
import com.example.se.entity.Comment;
import com.example.se.entity.Student;
import com.example.se.entity.dto.CommentRequest;
import com.example.se.entity.dto.DeleteRequest;
import com.example.se.mapper.StudentMapper;
import com.example.se.service.CommentService;
import com.example.se.service.PostService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@CrossOrigin
@RequestMapping("/comment")
@RestController
public class CommentController {
    public static String USER_LOGIN_STATE = "userLoginState";

    @Resource
    private PostService postService;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private CommentService commentService;

    /**
     * 发布帖子
     * @param commentRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @CrossOrigin
    public BaseResponse<Long> addPost(@RequestBody CommentRequest commentRequest, HttpServletRequest request){
        if (commentRequest == null) {
            System.out.println("参数为空");
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        Comment comment = new Comment();
        BeanUtils.copyProperties(commentRequest,comment);

        //校验
        Long postId = comment.getPostId();
        String content = comment.getContent();
        if (postId <= 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        if (StringUtils.isNotBlank(content) && content.length() > 512){
            return ResultUtils.error(40000,"没有内容或内容过长");
        }

        Student loginUser = getLoginUser(request);
        if (loginUser == null) {
            System.out.println("未登录");
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR);
        }
        comment.setUserId(loginUser.getId());
        boolean result = commentService.save(comment);
        if (!result) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR);
        }

        long newCommentId = comment.getId();
        return ResultUtils.success(newCommentId);
    }

    /**
     * 删除帖子
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("delete")
    @CrossOrigin
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request){
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        Student loginUser = getLoginUser(request);
        if (loginUser == null) {
            System.out.println("未登录");
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR);
        }

        Long commentId = deleteRequest.getId();
        Comment oldComment = commentService.getById(commentId);
        //判断是否存在
        if (oldComment == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        //仅本人可删除
        if (!oldComment.getUserId().equals(loginUser.getId())) {
            System.out.println("无删除权限");
            return ResultUtils.error(40001,"无权限");
        }

        boolean result = commentService.removeById(oldComment.getId());

        return ResultUtils.success(result);
    }

    public Student getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        Student currentUser = (Student) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            System.out.println("------未登录------");
            return null;
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        currentUser = studentMapper.selectById(userId);
        if (currentUser == null) {
            System.out.println("------未登录------");
            return null;
        }
        return currentUser;
    }
}
